package com.winit.core.ci.vcs.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * Created by wangjian on 16/8/2.
 */
public class VCSException extends Exception{

    private static final Logger logger = LoggerFactory.getLogger(VCSException.class);

    private static final String DEFAULT_DESC = "联系beetle管理员!";

    private String errDesc;

    public VCSException(String message){
        super(message);
        logger.error("VCSException:异常,e:"+message);
        this.errDesc = message;
    }

    public VCSException(Exception e){
        logger.error("VCSException:异常,e:"+e);
        this.setErrDesc(e,null);
    }

    public VCSException(Exception e, String svnPath){
        logger.error("VCSException:异常,e:"+e);
        this.setErrDesc(e,svnPath);
    }

    private void setErrDesc(Exception e,String otherMessage){
        String exceptionName = e.getClass().getSimpleName();
        String message = e.getMessage();
        String errDesc = message;
        if("NullPointerException".equals(exceptionName)){
            errDesc = "系统中存在空值,请"+this.DEFAULT_DESC;
        }else if("FileNotFoundException".equals(exceptionName)){
            errDesc = "文件未找到,请检查文件路径或"+this.DEFAULT_DESC;
        }else {
            if(message.contains("svn: E125002:")){
                errDesc = "svn地址错误,请检查svn地址是否正确!";
            }else if(message.contains("svn: E170001:")){
                errDesc = "svn用户验证失败,请检查svn登录用户名/密码是否正确!";
            }else if(message.contains("svn: E210003:")){
                errDesc = "连接svn服务器失败,请检查svn服务器是否启动或网络是否正常!";
            }else if(message.contains("svn: E170000:")){
                errDesc = "svn地址不存在,请检查svn地址是否正确!";
            }else if(message.contains("svn: E155018:")){
                errDesc = "svn检出本地路径已存在或者不是目录,请"+this.DEFAULT_DESC;
            }else if(message.contains("svn: E155007:")){
                errDesc = "指定的本地路径并不是svn本地仓库,请检查路径是否正确或"+this.DEFAULT_DESC;
            }else if(message.contains("svn: E155000:")){
                errDesc = "svn检出本地路径不存在,请"+this.DEFAULT_DESC;
            }
        }

        StringBuilder errBuilder = new StringBuilder();
        errBuilder.append(errDesc);

        if (StringUtils.hasText(otherMessage)){
            errBuilder.append("\r\n");
            errBuilder.append(otherMessage);
        }

        this.errDesc = errBuilder.toString();
    }

    public String getMessage(){
        return errDesc;
    }
}
